package com.atguigu.orderservice.controller;


import com.atguigu.commonutils.JwtUtils;
import com.atguigu.commonutils.R;
import com.atguigu.orderservice.entity.TOrder;
import com.atguigu.orderservice.service.TOrderService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

/**
 * <p>
 * 订单 前端控制器
 * </p>
 *
 * @author testjava
 * @since 2021-08-10
 */
@RestController
@RequestMapping("/eduorder/order")
@CrossOrigin
public class TOrderController {
    private TOrderService orderService;
    @Autowired
    public void setOrderService(TOrderService orderService) {
        this.orderService = orderService;
    }

    // 根据课程id与请求头的token信息来创建订单
    @PostMapping("/createOrder/{courseId}")
    public R save(@PathVariable String courseId, HttpServletRequest request) {
        String ucenterId = JwtUtils.getMemberIdByJwtToken(request);
        if(StringUtils.isEmpty(ucenterId)){
            return R.error().message("请先登录!");
        }
        String orderId = orderService.saveOrder(courseId, ucenterId);
        return R.ok().data("orderId", orderId);
    }

    // 根据订单id来获取订单id
    @GetMapping("/getOrder/{orderId}")
    public R getOrderById(@PathVariable String orderId){
        QueryWrapper<TOrder> wrapper = new QueryWrapper<>();
        wrapper.eq("order_no",orderId);
        TOrder order = orderService.getOne(wrapper);
        if(order == null){
            return R.error().message("未查询到该订单!");
        }
        return R.ok().data("item",order);
    }

    // 根据用户id与课程id来查询用户是否购买过该课程
    @GetMapping("/isBuyCourse/{memberid}/{id}")
    public boolean isBuyCourse(@PathVariable String  memberid,@PathVariable String id){
        System.out.println(id);
        System.out.println(memberid);
        int count = orderService.count(new QueryWrapper<TOrder>().eq("member_id", memberid).eq("course_id", id).eq("status", 1));
        if(count>0) {
            return true;
        } else {
            return false;
        }
    }
}

